package com.luyou.awt.menu;

import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.*;

/**
 * 右键菜单
 */
public class PopupMenuTest {

    private TextArea ta = new TextArea(4, 30);
    private Frame frame = new Frame("测试");
    PopupMenu pop = new PopupMenu();
    CheckboxMenuItem autoWrap = new CheckboxMenuItem("自动换行");

    MenuItem copyItem = new MenuItem("复制");
    MenuItem pasteItem = new MenuItem("粘贴");

    Menu format = new Menu("格式");
    //创建commentItem菜单 指定"ctrl + shift + /"快捷键 是ture就多一个shift
    MenuItem commentItem = new MenuItem("注释", new MenuShortcut(KeyEvent.VK_SLASH, true));
    MenuItem cancelItem = new MenuItem("取消注释");

    public void init(){
        ActionListener menuListener = e ->{
            String cmd = e.getActionCommand();
            ta.append("单击”" + cmd+"”菜单"+ "\n");
            if(cmd.equals("退出")){
                System.exit(0);
            }
        };
        //为commentItem菜单添加事件监听
        commentItem.addActionListener(menuListener);
        //为pop添加菜单
        pop.add(autoWrap);
        pop.addSeparator();
        pop.add(copyItem);
        pop.add(pasteItem);

        //为format菜单添加菜单项
        format.add(commentItem);
        format.add(cancelItem);
        //使用new MenuItem的方式添加菜单分隔线
        pop.add(new MenuItem("-"));
        pop.add(format);

        Panel panel = new Panel();
        panel.setPreferredSize(new Dimension(300, 160));
        panel.add(pop);
        panel.addMouseListener(new MouseInputAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                //如果释放的是鼠标右键
                if(e.isPopupTrigger()){
                    pop.show(panel, e.getX(), e.getY());
                }
            }
        });

        frame.add(panel);
        frame.add(ta, BorderLayout.NORTH);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        new PopupMenuTest().init();
    }
}
